#include <stdio.h>
#include <stdlib.h>


//设定一个结构体A，存放队列的头尾指针
//定义一个单向链表B，存放数据
//A的头指针指向B的头，头插时直接对B操作
//A的尾指针指向B的尾，尾删时直接对B操作
//进行添加或删除操作时，直接拿A的名称进行操作

typedef int linkqueue_data_t;
typedef struct linkqueue_node {
    linkqueue_data_t data;
    struct linkqueue_node *next;
} linkqueue_node_t;

typedef struct linkqueue {
    linkqueue_node_t *head;
    linkqueue_node_t *tail;
} linkqueue_t;

linkqueue_t *create_linkqueue() 
{
    linkqueue_t *lq;
    lq = malloc(sizeof(linkqueue_t));
    lq->head = malloc(sizeof(linkqueue_node_t));
    lq->tail = lq->head;
    lq->head->next = NULL;
    return lq;
}

int in_linkqueue(linkqueue_t *lq, const linkqueue_data_t data) 
{
    //1. 执行尾部插入
    //2. 保存新的尾节点地址
    linkqueue_node_t *newnode;
    newnode = malloc(sizeof(linkqueue_node_t));
    newnode->data = data;
    newnode->next = NULL;//;lq->tail->next;
    lq->tail->next = newnode;
    lq->tail = newnode;
    return 0;
}

int out_linkqueue(linkqueue_t *lq, linkqueue_data_t *databuf) 
{
    if(NULL == lq->head->next) {
        return -1;
    } else {
    }
    //1.执行出队
    //2.是否需要 纠正尾节点地址
    linkqueue_node_t *temp;
    temp = lq->head->next;
    lq->head->next = temp->next;
    *databuf = temp->data;
    free(temp);

    if(NULL == lq->head->next)
        lq->tail = lq->head;
    return 0;
}

int get_head_linkqueue(linkqueue_t *lq, linkqueue_data_t *databuf)
{
    if(NULL == lq->head->next) return -1;
    *databuf = lq->head->next->data;
    return 0;
}

int is_empty_linkqueue(linkqueue_t *lq)
{
    return NULL == lq->head->next;
}

int clean_linkqueue(linkqueue_t *lq) {
    linkqueue_node_t *t1, *t2;
    t2 = lq->head->next;
    while(NULL != t2) {
        t1 = t2;
        t2 = t2->next;
        free(t1);
    }
    lq->head->next = NULL;
    lq->tail = lq->head;
    return 0;
}

int des_linkqueue(linkqueue_t **pp) {
    clean_linkqueue(*pp);
    free((*pp)->head);
    free((*pp));
    pp = NULL;
}

void print_linkqueue(linkqueue_t *lq) {
    linkqueue_node_t *head;
    head = lq->head;

    while(NULL != head->next) {
        head = head->next;
        printf("%d ", head->data);
    }
    printf("\n");
}

int main( int argc, const char *argv[]) 
{
    linkqueue_t *lq;
    linkqueue_data_t buf;
    lq = create_linkqueue();

    in_linkqueue(lq, 10);
    in_linkqueue(lq, 20);
    in_linkqueue(lq, 30);
    in_linkqueue(lq, 40);
    in_linkqueue(lq, 50);
    print_linkqueue(lq);
}

